import { useEffect, useMemo, useState } from 'react'
import PageComponent from '@components/pageComponent'
import style from './index.module.less'
import { Button, Dialog, Form, Input, TextArea, Toast } from 'antd-mobile'
import Selector from '@components/selector'
import Dictionary from '@js/dictionary'
import CardPicker from '@components/formCardPicker'
import { awaitWrap, filterRepeat } from '@src/assets/js/tool'
import { partyRequest, getPartyRequest, delPartyRequest } from './ajax'
import PageLoading from '@components/pageLoading'
import { useAppDispatch, useAppSelector } from '@src/redux/hook'
import { refreshCaseEditVersion } from '@src/redux/reducers/cases'
import { pop } from '@src/redux/reducers/pages'
import CompanyNameInput from '@components/companyNameInput'

const { useForm, Item, useWatch } = Form

const keys = ['legal', 'area', 'contact', 'deliver_address_type', 'deliver_address', 'mobile', 'email', 'tel']

async function initParty (id, formRef, setData, setLoading) {
  setLoading(true)
  const [e, d] = await awaitWrap(getPartyRequest(id))
  setLoading(false)
  if (e === null && d !== null) {
    initFormData(d, formRef)
    setData(d)
  }
}

function formatSubmitData (d, caseid, isApply) {
  keys.map(k => {
    if (!d[k]) {
      d[k] = null
    }
  })
  d.caseid = caseid
  d.type = isApply ? '申请人' : '被申请人'
  d.address_type = d.address_type instanceof Array && d.address_type.length > 0 ? d.address_type[0] : undefined
  d.deliver_address_type = d.deliver_address_type instanceof Array && d.deliver_address_type.length > 0 ? d.deliver_address_type[0] : undefined
  d.license_type = d.license_type instanceof Array && d.license_type.length > 0 ? d.license_type[0] : undefined
  d.area = d.area instanceof Array && d.area.length > 0 ? d.area[0] : undefined
  d.tag = JSON.stringify({ subject_type_tag: d.subject_type_tag[0] })
}

function initFormData (d, formRef) {
  const keys = Object.keys(d)
  keys.forEach(k => {
    if (d[k] === null) {
      d[k] = undefined
    }
  })
  if (d.address_type) {
    d.address_type = [d.address_type]
  }
  if (d.deliver_address_type) {
    d.deliver_address_type = [d.deliver_address_type]
  }
  if (d.license_type) {
    d.license_type = [d.license_type]
  }
  if (d.area) {
    d.area = [d.area]
  }
  if (d.subject_type_tag) {
    d.subject_type_tag = [d.subject_type_tag]
  }
  if (d.file instanceof Array && d.file.length > 0) {
    d.front = d.file[0]
  }
  if (d.file1 instanceof Array && d.file1.length > 0) {
    d.back = d.file1[0]
  }
  formRef.setFieldsValue(d)
}

async function submitHandle (d, caseid, isApply, dispatch) {
  formatSubmitData(d, caseid, isApply)
  Toast.show({ content: '提交中', icon: 'loading', duration: 0 })
  const [e] = await awaitWrap(partyRequest(d))
  if (e === null) {
    dispatch(refreshCaseEditVersion())
    Toast.clear()
    Toast.show({ content: '提交成功', icon: 'success' })
    setTimeout(() => {
      dispatch(pop())
    }, 500)
  }
}

async function delHandle (id, dispatch) {
  Toast.show({ content: '删除中', icon: 'loading', duration: 0 })
  const [e] = await awaitWrap(delPartyRequest(id))
  if (e === null) {
    dispatch(refreshCaseEditVersion())
    Toast.clear()
    Toast.show({ content: '删除成功', icon: 'success' })
    setTimeout(() => {
      dispatch(pop())
    }, 500)
  }
}

function renderBlockByIdentityType (identityType, areaList, formRef) {
  if (identityType === '企业') {
    return (
      <Item name='legal' label='法定代表人'>
        <Input placeholder='请输入法定代表人' clearable />
      </Item>
    )
  }
  return (
    <>
      <Selector name='area' label='所在地' rules={[{ required: true, message: '所在地不能为空' }]} options={areaList} formRef={formRef} />
      <Item label='证件照正面' name='front'>
        <CardPicker isFront />
      </Item>
      <Item label='证件照背面' name='back'>
        <CardPicker />
      </Item>
    </>
  )
}

function Main ({ meta = { apply: false, id: '', caseid: '' } }) {
  const userInfo = useAppSelector(state => state.basic.userInfo)
  const dispatch = useAppDispatch()
  const [formRef] = useForm()
  const subjectType = useWatch('subject_type', formRef)
  const [options1, setOptions1] = useState([])
  const [options2, setOptions2] = useState([])
  const [options3, setOptions3] = useState([])
  const [options4, setOptions4] = useState([])
  const [options5, setOptions5] = useState([])
  const [options6, setOptions6] = useState([])
  const [data, setData] = useState(null)
  const [loading, setLoading] = useState(false)
  const isCompany = useMemo(() => {
    return subjectType === '企业'
  }, [subjectType])
  const licenseTypes = useMemo(() => {
    const l = isCompany ? options2 : options3
    return l.map(li => li.title)
  }, [isCompany, options2, options3])
  const optionNames = useMemo(() => {
    return options1.map(li => ({ label: li.title, value: li.title }))
  }, [options1])
  const id = useMemo(() => {
    return meta && meta.id ? meta.id : ''
  }, [meta])
  const caseid = useMemo(() => {
    return meta && meta.caseid ? meta.caseid : ''
  }, [meta])
  const isEdit = useMemo(() => {
    return id !== ''
  }, [id])
  const isApply = useMemo(() => {
    return meta.apply
  }, [meta])
  const isMe = useMemo(() => {
    return !!data && userInfo.id === data.accountid
  }, [userInfo, data])
  const title = useMemo(() => {
    const l = []
    if (isEdit) {
      l.push('编辑')
    } else {
      l.push('添加')
    }
    if (isApply) {
      l.push('申请人')
    } else {
      l.push('被申请人')
    }
    return l.join('')
  }, [isEdit, isApply])
  useEffect(() => {
    const d = new Dictionary()
    d.init('主体类型,所在地,送达地址类型,当事人选择送达地址类型,企业证件类型,自然人证件类型')
      .then(() => {
        setOptions1(d.getList('主体类型'))
        setOptions2(d.getList('企业证件类型'))
        setOptions3(d.getList('自然人证件类型'))
        setOptions4(filterRepeat(d.getList('所在地').map(li => li.title)))
        setOptions5(filterRepeat(d.getList('送达地址类型').map(li => li.title)))
        setOptions6(filterRepeat(d.getList('当事人选择送达地址类型').map(li => li.title)))
      })
  }, [])
  useEffect(() => {
    if (id && formRef) {
      initParty(id, formRef, setData, setLoading)
    }
  }, [id, formRef])
  if (loading) {
    return (
      <PageComponent title={title}><PageLoading /></PageComponent>
    )
  }
  return (
    <PageComponent title={title}>
      <div className={style.container}>
        <div className={style.notice}>
          <div>1、当事人信息自动获取由第三方服务接口提供，仅供预立案参考，请核对信息无误后再提交案件。</div>
          <div>2、手机号码请填写当事人手机号，请勿填写代理人手机号。</div>
        </div>
        <Form layout='horizontal' form={formRef} onFinish={d => {
          Dialog.confirm({
            title: '您确定要提交吗？',
            onConfirm: () => {
              submitHandle(d, caseid, isApply, dispatch)
            }
          })
        }}>
          <Item name='id' noStyle><span /></Item>
          <Item name='subject_type' noStyle><span /></Item>
          <Item name='type' noStyle><span /></Item>
          <Selector name='subject_type_tag' label='主体类型' rules={[{ required: true, message: '主体类型不能为空' }]} disabled={isMe} options={optionNames} formRef={formRef} onChange={v => {
            if (!v) {
              formRef.setFieldsValue({
                license_type: [],
                subject_type: undefined
              })
            } else {
              const o = options1.find(li => li.title === v)
              if (o) {
                formRef.setFieldsValue({
                  license_type: [],
                  subject_type: o.value
                })
              }
            }
          }} />
          {
            isCompany ? (
              <CompanyNameInput formRef={formRef} name='name' label='公司名称' rules={[{ required: true, message: '公司名称不能为空' }]} />
            ) : (
              <Item label='姓名' name='name' disabled={isMe} rules={[{ required: true, message: '姓名不能为空' }]}>
                <Input placeholder='请输入' clearable />
              </Item>
            )
          }
          <Selector name='license_type' label='证件类型' disabled={isMe} rules={[{ required: true, message: '证件类型不能为空' }]} options={licenseTypes} formRef={formRef} />
          <Item name='license' label='证件号码' disabled={isMe} rules={[{ required: true, message: '证件号码不能为空' }]}>
            <Input placeholder='请输入' clearable />
          </Item>
          {renderBlockByIdentityType(subjectType, options4, formRef)}
          <Selector name='address_type' label='地址类型' rules={[{ required: true, message: '地址类型不能为空' }]} options={options5} formRef={formRef} />
          <Item name='address' label='地址' rules={[{ required: true, message: '地址不能为空' }]}>
            <TextArea placeholder='请输入' clearable autoSize={{ minRows: 3 }} />
          </Item>
          <Item name='contact' label='收件人'>
            <Input placeholder='请输入' clearable />
          </Item>
          <Selector name='deliver_address_type' label='送达地址类型' options={options6} formRef={formRef} />
          <Item name='deliver_address' label='送达地址'>
            <TextArea placeholder='请输入' clearable autoSize={{ minRows: 3 }} />
          </Item>
          <Item name='mobile' label='手机号码'>
            <Input placeholder='请输入' clearable />
          </Item>
          <Item name='email' label='邮箱'>
            <Input placeholder='请输入' clearable />
          </Item>
          <Item name='tel' label='固定电话'>
            <Input placeholder='请输入' clearable />
          </Item>
          <Item>
            <div className={style.btns}>
              <Button type='submit' color='primary' block>提交</Button>
              {id && !isMe && <Button className={style.del} block onClick={() => {
                Dialog.confirm({
                  title: '您确定要删除吗？',
                  onConfirm: () => {
                    delHandle(id, dispatch)
                  }
                })
              }}>删除</Button>}
            </div>
          </Item>
        </Form>
      </div>
    </PageComponent>
  )
}

export default Main
